import { memo, useEffect, useState } from 'react';
import VideoUtil from '@/utils/video.js';
import { Flex, Spin } from 'antd';

/**
 * 读取视频第一帧作为图片展示
 *
 * @param {object} props 属性
 * @param {string} props.url 视频地址
 * @param {number} props.height 高度
 * @param {function} props.onSuccess 成功回调
 */
function VideoFirstFrame({ url, height, ...props }) {
  const [isSuccess, setIsSuccess] = useState(true);
  const [isLoading, setIsLoading] = useState(false);
  const [firstFrame, setFirstFrame] = useState('');

  useEffect(() => {
    setIsLoading(true);
    VideoUtil.getVideoFirstFrame(url)
      .then((base64) => {
        setFirstFrame(base64);
        setIsLoading(false);
        setIsSuccess(true);
        if (props?.onSuccess) {
          props.onSuccess(base64);
        }
      })
      .catch(() => {
        setIsSuccess(false);
      });
  }, [url]);

  if (isLoading) {
    return (
      <Spin spinning={true} tip="正在加载...">
        <div style={{ height: height, minWidth: '100px' }}></div>
      </Spin>
    );
  }

  if (!isSuccess) {
    return (
      <Flex
        align="center"
        justify="center"
        style={{ height: height, width: '100%', backgroundColor: '#f5f5f5' }}
      >
        无法加载视频图片
      </Flex>
    );
  }

  return (
    <img
      alt="文件图"
      src={firstFrame}
      style={{ height: height, objectFit: 'cover', width: '100%' }}
      loading="lazy"
    />
  );
}

export default memo(VideoFirstFrame);
